package com.javasm.commons;

import com.javasm.Service.LoginPhoneService;
import com.javasm.entity.LoginUser;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
public class PhoneAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private LoginPhoneService loginPhoneService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PhoneCaptchaAuthenticationToken token = (PhoneCaptchaAuthenticationToken) authentication;
        String phone = (String) token.getPrincipal();
        String captcha = (String) token.getCredentials();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String attribute = (String) request.getSession().getAttribute("phoneCaptcha");
        if (attribute==null)throw new BadCredentialsException("验证码已经过期，请重新发送验证码");
        if (!captcha.equals(attribute))throw new BadCredentialsException("验证码不正确");
        LoginUser loginUser = (LoginUser) loginPhoneService.loadUserByUsername(phone);
        if (loginUser==null)throw new BadCredentialsException("用户不存在，请注册");
        PhoneCaptchaAuthenticationToken authenticationResult
                =new PhoneCaptchaAuthenticationToken(loginUser,captcha,loginUser.getAuthorities());
        authenticationResult.setDetails(token.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return PhoneCaptchaAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
